package com.study.cloud.gateway.core.filter;

import com.study.cloud.gateway.core.context.GatewayContext;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wangwancheng
 * @create 2025/7/20 15:22
 */
@Slf4j
@Data
public class GatewayFilterChain {

    private List<FilterInterface> filters = new ArrayList<>();

    /**
     * 批量添加过滤器
     * 过滤器时在规则Rule中配置， 这规则时在nacos中配置， 可能是多个
     *
     * @param filterInterface
     * @return
     */

    public GatewayFilterChain addFilterList(List<FilterInterface> filterInterfaceList) {
        filters.addAll(filterInterfaceList);
        return this;
    }

    public GatewayContext doFilter(GatewayContext context) throws Exception {
        if (filters.isEmpty()){
            return context;
        }
        //执行过滤器
        for (FilterInterface filterInterface : filters) {
            try {
                filterInterface.doFilter(context);
            }catch (Exception e){
                log.error("doFilter error",e);
                throw e;
            }
        }
        return context;
    }

}
